<template>
  <div class="categories">
    <!-- 面包屑区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item><a href="/">商品管理</a></el-breadcrumb-item>
      <el-breadcrumb-item>商品分类</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片区域 -->
    <el-card>
      <!-- 添加分类按钮 -->
      <el-row>
        <el-button type="primary" @click="addCategoryBtn">添加分类</el-button>
      </el-row>
      <!-- 分类表单区域 -->
      <el-table
        :data="categoriesList"
        border
        style="width: 100%"
        row-key="cat_id"
        :tree-props="{children: 'children', hasChildren: true}">
        <el-table-column prop="cat_name" label="分类名称" width="250"></el-table-column>
        <el-table-column prop="cat_deleted" label="是否有效" >
          <template v-slot="scope">
            <i class="el-icon-success" style="color: lightgreen;" v-show="!scope.row.cat_deleted"></i>
            <i class="el-icon-error" style="color: red;" v-show="scope.row.cat_deleted"></i>
          </template>
        </el-table-column>
        <el-table-column prop="cat_level" label="排序" >
          <template v-slot="scope">
            <el-tag v-if="scope.row.cat_level === 0">一级</el-tag>
            <el-tag v-if="scope.row.cat_level === 1" type="success">二级</el-tag>
            <el-tag v-if="scope.row.cat_level === 2" type="warning">三级</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="cat_name" label="操作">
          <template v-slot="scope">
            <el-button type="primary" icon="el-icon-edit" size="mini" @click="showEditDialog(scope.row)">编辑</el-button>
            <el-button type="danger" icon="el-icon-delete" size="mini" @click="deleteCategories(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 添加分类对话框 -->
    <el-dialog
      title="添加分类"
      :visible.sync="addCategoryDialogVisible"
      width="50%"
      @close="addCategoryClose">
      <!-- 添加分类表单 -->
      <el-form ref="addCategoryFormRef" :rules="addCategoryFormRules" :model="addCategoryForm" label-width="100px">
        <el-form-item label="分类名称：" prop="cat_name">
          <el-input v-model="addCategoryForm.cat_name"></el-input>
        </el-form-item>
        <el-form-item label="父级分类：" prop="cat_name">
          <!-- options 用来指定数据源 -->
          <el-cascader
            v-model="selectKeys"
            :options="parentCategoriesList"
            :props="{ expandTrigger: 'hover',
                      value: 'cat_id',
                      label: 'cat_name',
                      children: 'children',
                      checkStrictly: true }"
            @change="parentCategoriesChanged" clearable>
          </el-cascader>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addCategoryDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="sureAddCategory">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 修改分类对话框 -->
    <el-dialog
      title="修改分类"
      :visible.sync="editCategoryDialogVisible"
      width="50%"
      @close="editCategoryClose">
      <!-- 添加分类表单 -->
      <el-form ref="editCategoryFormRef" :rules="editCategoryFormRules" :model="editCategoryForm" label-width="100px">
        <el-form-item label="分类名称：" prop="cat_name">
          <el-input v-model="editCategoryForm.cat_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editCategoryDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="sureEditCategory">确 定</el-button>
      </span>
    </el-dialog>

  </div>
</template>

<script>
import { getCategoriesList, addCategoriesList, editCategoriesList, deleteCategoriesList } from 'network/goods_category'

export default {
  name: "Categories",
  data() {
    return {
      // 查询条件
      queryInfo: { 
        type: 3,
        // pagenum: 2,
        pagesize: 5
      },

      // 所有商品分类列表
      categoriesList: [],

      // 父级商品分类列表
      parentCategoriesList: [],

      // 添加分类对话框的显示和隐藏
      addCategoryDialogVisible: false,

      // 修改分类对话框的显示和隐藏
      editCategoryDialogVisible: false,

      // 选中的父级分类的Id数组
      selectKeys: [],

      // 树形控件的属性绑定对象
      treeProps: {
        label: 'cat_name',
        children: 'children'
      },

      // 添加分类的表单数据对象
      addCategoryForm: {
        // 将要添加分类的名称
        cat_name: '',
        // 将要添加分类的父ID 如果要添加1级分类，则父分类id应设置为 0
        cat_pid: 0,
        // 将要添加分类的层级 默认0 可以为0|1|2
        cat_level: 0
      },

      // 修改分类的表单数据对象
      editCategoryForm: {
        cat_name: ''
      },

      // 添加分类表单的验证规则对象
      addCategoryFormRules: {
        cat_name: [
          { required: true, message: '请输入分类名称', trigger: 'blur' }
        ]
      },

      // 修改分类表单的验证规则对象
      editCategoryFormRules: {
        cat_name: [
          { required: true, message: '请输入分类名称', trigger: 'blur' }
        ]
      }
    }
  },

  created() {
    this.getCategoriesList()
  },

  methods: {
    // 获取商品分类数据列表
    getCategoriesList() {
      getCategoriesList(this.queryInfo).then(res => {
        // console.log(res);
        if(res.meta.status !== 200) return this.$message.error(res.meta.msg)
        this.categoriesList = res.data
        // console.log(this.categoriesList);
      })
    },

    // 获取父级分类的数据列表
    getParentCategoriesList() {
      getCategoriesList({type: 2 }).then(res => {
        if(res.meta.status !== 200) return this.$message.error(res.meta.msg)
        this.parentCategoriesList = res.data
      })
    },

    // 父级选择项发送改变触发这个函数 
    parentCategoriesChanged() {
      console.log(this.selectKeys);
      // 如果selectedKeys 数组中的 length 大于0 ，证明选中的父级分类
      // 反之 说明没有选中任何父级分类
      if(this.selectKeys.length > 0) {
        // 父级分类的ID
        this.addCategoryForm.cat_pid = this.selectKeys[this.selectKeys.length - 1]
        // 为当前分类的等级赋值
        this.addCategoryForm.cat_level = this.selectKeys.length
        return
      } else {
        // 父级分类的ID
        this.addCategoryForm.cat_pid = 0
        // 为当前分类的等级赋值
        this.addCategoryForm.cat_level = 0
      }
      
    },

    // 添加商品分类 按钮
    addCategoryBtn() {
      this.getParentCategoriesList()
      this.addCategoryDialogVisible = true
    },

    // 修改商品分类 按钮
    showEditDialog(row) {
      this.editCategoryForm = row
      // console.log(this.editCategoryForm);
      this.editCategoryDialogVisible = true
    },

    // 删除商品分类
    deleteCategories(row) {
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          deleteCategoriesList(row.cat_id).then(res => {
            if(res.meta.status !== 200 ) return this.$message.error(res.meta.msg)
            this.getCategoriesList()
            this.$message.success(res.meta.msg)
          }).catch(err => this.$message.error(err))
        }).catch(err => this.$message.error(err))
    },

    // 确认添加商品分类
    sureAddCategory() {
      this.$refs.addCategoryFormRef.validate(valid => {
        if(!valid) return
        addCategoriesList(this.addCategoryForm).then(res => {
          if(res.meta.status !== 201) return this.$message.error(res.meta.msg)
          this.getCategoriesList()
          this.addCategoryDialogVisible = false
        }).catch(err => { this.$message.error(err) })
      })
    },

    // 确认修改商品分类
    sureEditCategory() {
      this.$refs.editCategoryFormRef.validate(valid => {
        if(!valid) return
        editCategoriesList(this.editCategoryForm.cat_id, { cat_name: this.editCategoryForm.cat_name}).then(res => {
          if(res.meta.status !== 200 ) return this.$message.error(res.meta.msg)
          this.$message.success(res.meta.msg)
          this.getCategoriesList()
          this.editCategoryDialogVisible = false
        }).catch(err => { this.$message.error(err) })
      })
    },

    // 监听添加分类对话框的关闭事件
    addCategoryClose() {
      this.$refs.addCategoryFormRef.resetFields()
      this.selectKeys = []
      this.addCategoryForm.cat_level = 0
      this.addCategoryForm.cat_pid = 0
    },

    // 监听修改分类对话框的关闭事件
    editCategoryClose() {
      this.$refs.editCategoryFormRef.resetFields()
    }
  }
}
</script>

<style>
  .el-breadcrumb,
  .el-row {
    margin-bottom: 20px;
  }

  .el-cascader {
    height: 30px;
  }
</style>